from configparser import ConfigParser
import MySQLdb
import time
import logging
import threading


# mysql 操作
def MysqlOper(cmd):
    cp = ConfigParser()
    cp.read('db.cfg')
    section = cp.sections()[0]
    cnx = MySQLdb.connect(cp.get(section, 'host'), cp.get(section, 'user'), cp.get(section, 'password'),
                          cp.get(section, 'db'))
    cursor = cnx.cursor()
    try:
        sqlcmd = cp.get(cmd, 'cmd')
        cursor.execute(sqlcmd.replace("\'", r"'"))
        cnx.commit()
        # data = cursor.fetchall()
        # print(data)
        LogOper('已执行' + cmd + '！')
    except:
        cnx.rollback()
        LogOper('操作数据库' + cmd + '失败！')
    cnx.close()


# 操作日志
def LogOper(log):
    logger.info(log)
    return


def Looper(operName):
    while True:
        # print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        cp = ConfigParser()
        cp.read('db.cfg')
        runtime = cp.get(operName, 'runtime')
        MysqlOper(operName)
        time.sleep(int(runtime))
    return


class NewThread(threading.Thread):
    def __init__(self, threadID, tName):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = tName

    def run(self):
        LogOper('开始执行线程' + self.name)
        LogOper(self.name)
        Looper(self.name)


cp = ConfigParser()
cp.read('db.cfg')
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler('RunLog.txt')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(handler)
logger.addHandler(console)
threadLock = threading.Lock()
threads = []  # 线程池
threadID = 1  # 线程ID

for config in cp.sections():
    if config != 'db_setting':
        try:
            thread = NewThread(threadID, config)
            thread.start()
            threads.append(thread)
            threadID += 1
        except:
            LogOper('创建线程' + config + '失败！')
